package com.enzoism.springboot.dive.service;

import com.enzoism.springboot.dive.model.UserMsg;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class CacheService2 {

    @Cacheable(value = "userListCache", cacheManager = "ehCacheManager")
    public List<UserMsg> initUserList() {
        List<UserMsg> userMsgList = new ArrayList<>();
        userMsgList.add(new UserMsg("001", "10"));
        userMsgList.add(new UserMsg("002", "10"));
        userMsgList.add(new UserMsg("003", "10"));
        userMsgList.add(new UserMsg("004", "10"));
        return userMsgList;
    }

    @Cacheable(value = "userByIdCache", key = "#id", cacheManager = "ehCacheManager")
    public UserMsg findById(final Long id) {
        List<UserMsg> userMsgList = initUserList();
        for (UserMsg user : userMsgList) {
            if (user.getId().equals(id)) {
                return user;
            }
        }
        return null;
    }

    @CacheEvict(value = "userByIdCache", key = "#user.id", cacheManager = "ehCacheManager") //移除指定key的数据
    public UserMsg delete(UserMsg user) {
        List<UserMsg> userMsgList = initUserList();
        userMsgList.remove(user);
        return user;
    }

    @CacheEvict(value = "userListCache", allEntries = true, cacheManager = "ehCacheManager") //移除所有数据
    public void deleteAll() {
        List<UserMsg> userMsgList = initUserList();
        userMsgList.clear();
    }

    @CachePut(value = "userListCache", key = "#user.id", cacheManager = "ehCacheManager")
    public UserMsg save(UserMsg user) {
        List<UserMsg> userMsgList = initUserList();
        return user;
    }

}
